package com.lottery.im.module.setting.presenter;

import android.app.Activity;
import com.lottery.im.MyApplication;
import com.lottery.im.api.Api;
import com.lottery.im.api.ApiClient;
import com.lottery.im.api.observer.BaseObserver;
import com.lottery.im.api.result.entity.FaceUrl;
import com.lottery.im.base.BaseFragmentPresenter;
import com.lottery.im.module.setting.view.SettingView;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMFriendGenderType;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.TIMValueCallBack;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.android.FragmentEvent;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import java.io.File;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class SettingPresenter extends BaseFragmentPresenter<SettingView> {

  public SettingPresenter(Activity activity,
      SettingView iView,
      LifecycleProvider<FragmentEvent> provider) {
    super(activity, iView, provider);
  }

  /**
   * 获取自己的IM资料
   */
  public void getSelfProfile() {
    TIMFriendshipManager.getInstance().getSelfProfile(new TIMValueCallBack<TIMUserProfile>() {
      @Override public void onError(int i, String s) {

      }

      @Override public void onSuccess(TIMUserProfile timUserProfile) {
        if (null != iView) iView.getSelfProfileSuce(timUserProfile);
      }
    });
  }

  /**
   * 修改性别 ，只修改IM那边，服务器无这个字段
   *
   * @param type 1男 2女
   */
  public void setSex(int type) {
    iView.showLoadingDialog();
    TIMFriendshipManager.ModifyUserProfileParam param =
        new TIMFriendshipManager.ModifyUserProfileParam();
    if (type == 1) {
      param.setGender(TIMFriendGenderType.Male);
    } else {
      param.setGender(TIMFriendGenderType.Female);
    }

    TIMFriendshipManager.getInstance().modifyProfile(param, new TIMCallBack() {
      @Override
      public void onError(int code, String desc) {
        if (null == iView) return;
        iView.showToast("修改失败,请稍后再试～");
        iView.cancelLoadingDialog();
      }

      @Override
      public void onSuccess() {
        if (null == iView) return;
        iView.setSexSuc(type);
        iView.cancelLoadingDialog();
      }
    });
  }

  /**
   * 个人头像修改（先上传自己的服务器，再将URL上传至TIM）
   *
   * @param path 文件地址
   */
  public void uploadUserHeadImg(String path) {

    File file = new File(path);
    MultipartBody.Builder builder = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)//表单类型
        .addFormDataPart("userId", MyApplication.getInstance().getUserInfo().getUserId())
        .addFormDataPart("token", MyApplication.getInstance().getToken());
    RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
    builder.addFormDataPart("userHeadImg", file.getName(), imageBody);//imgfile 后台接收图片流的参数名
    List<MultipartBody.Part> parts = builder.build().parts();

    ApiClient.getApiRetrofitInstance()
        .uploadUserHeadImg(parts)
        .throttleFirst(2, TimeUnit.SECONDS)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .compose(provider.bindToLifecycle())
        .subscribe(new BaseObserver<FaceUrl>() {
          @Override public void onStart() {
            iView.showLoadingDialog();
          }

          @Override public void onSuccess(FaceUrl groupFaceUrl) {

            TIMFriendshipManager.ModifyUserProfileParam param =
                new TIMFriendshipManager.ModifyUserProfileParam();
            param.setFaceUrl(Api.BASEADDRESS + groupFaceUrl.getUserHeadImg());

            TIMFriendshipManager.getInstance().modifyProfile(param, new TIMCallBack() {
              @Override
              public void onError(int code, String desc) {
                if (null == iView) return;
                iView.showToast("上传失败，请稍后再试");
                iView.cancelLoadingDialog();
              }

              @Override
              public void onSuccess() {
                if (null == iView) return;
                iView.updateFaceUrl(groupFaceUrl.getUserHeadImg());
                iView.cancelLoadingDialog();
              }
            });
          }

          @Override public void onFail(String code, String msg) {
            iView.showToast(msg);
            iView.cancelLoadingDialog();
          }

          @Override public void onException(String msg) {

          }

          @Override public void onFinish() {

          }
        });
  }
}
